﻿/*************************************************************************************
 * 文 件 名:   HK_MakeGroup
 * 
 * 描    述:   对选中的物体进行打组操作
 * 
 * 版    本：  V1.1
 * 创 建 者：  京产肠饭
 * 创建时间：  2021/8/25
 * 链   接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using UnityEditor;
using UnityEngine;

namespace HKTools
{
    [InitializeOnLoad]
    public class HK_MakeGroup
    {
        const int MakeGroupPriority = 1;

        [MenuItem("HKTools/MakeGroup(打组工具) %g", validate = true, priority = MakeGroupPriority)]
        static bool MakeGroupValidate()
        {
            return HK_ToolStates.IsActiveMakeGroup;
        }

        [MenuItem("HKTools/MakeGroup(打组工具) %g", priority = MakeGroupPriority)]
        public static void MakeGroup()
        {
            if (Selection.gameObjects.Length == 0)
            {
                Debug.Log("<color=red>错误: 未选中物体，无法执行打组操作</color>");
                return;
            }

            GameObject go;

            if (Selection.gameObjects[0].GetComponent<RectTransform>() != null)
            {
                go = new GameObject("Parent_Go", typeof(RectTransform));
            }
            else
            {
                go = new GameObject("Parent_Go");
            }

            go.transform.SetParent(Selection.gameObjects[0].transform.parent, false);

            Undo.RegisterCreatedObjectUndo(go, "CreateParent");

            Vector3 pos = Vector3.zero;

            foreach (var item in Selection.gameObjects)
            {
                pos += item.transform.position;
            }

            pos = pos / Selection.gameObjects.Length;

            go.transform.position = pos;

            foreach (var item in Selection.gameObjects)
            {
                Undo.SetTransformParent(item.transform, go.transform, "SetParent");
            }

            Selection.activeGameObject = null;
        }
    }
}